package com.learn.fragment.dynamic;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity implements OnClickListener {

    private LinearLayout mTabFriend;
    private LinearLayout mTabContact;
    private LinearLayout mTabSettings;

    private FriendFragment mFriend;
    private ContactFragment mContact;
    private SettingsFragment mSettings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化控件和声明事件
        mTabFriend = (LinearLayout) findViewById(R.id.id_tab_bottom_friend);
        mTabFriend.setOnClickListener(this);

        mTabContact = (LinearLayout) findViewById(R.id.id_tab_bottom_contact);
        mTabContact.setOnClickListener(this);

        mTabSettings = (LinearLayout) findViewById(R.id.id_tab_bottom_settings);
        mTabSettings.setOnClickListener(this);

        // 设置默认的Fragment
        setDefaultFragment();
    }

    private void setDefaultFragment() {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        mFriend = new FriendFragment();
        transaction.replace(R.id.id_content, mFriend);
        transaction.commit();
    }

    @Override
    public void onClick(View v) {
        FragmentManager fm = getFragmentManager();
        // 开启Fragment事务
        FragmentTransaction transaction = fm.beginTransaction();

        switch (v.getId()) {
            case R.id.id_tab_bottom_contact:
                if (mContact == null) {
                    mContact = new ContactFragment();
                }
                transaction.replace(R.id.id_content, mContact);
                break;
            case R.id.id_tab_bottom_settings:
                if (mSettings == null) {
                    mSettings = new SettingsFragment();
                }
                transaction.replace(R.id.id_content, mSettings);
                break;
            case R.id.id_tab_bottom_friend:
                if (mFriend == null) {
                    mFriend = new FriendFragment();
                }
                transaction.replace(R.id.id_content, mFriend);
                break;
        }
        // 事务提交
        transaction.commit();
    }
}
